﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace Architecture.Api.Controllers
{
    /// <summary>
    /// 文件管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="webHostEnvironment"></param>
        public FileController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FileUpload(IFormFile file)
        {
            var folder = Path.Combine(_webHostEnvironment.WebRootPath, "Images");
            var path = Path.Combine(folder, file.FileName);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            using (var fs = new FileStream(path, FileMode.CreateNew))
            {
                file.CopyTo(fs);
            }

            return Ok($"Images/{file.FileName}");
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadFile(IFormFile file)
        {
            var filePath = Directory.GetCurrentDirectory()+@"\wwwroot\Images\"+file.FileName;
            using (var fs = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            return Ok(file.FileName);
        }
    }
}
